//
//  Musics.swift
//  MyEcho
//
//  Created by longlong on 16/1/29.
//  Copyright © 2016年 LongLong. All rights reserved.
//

import Foundation
import CoreData

class Musics: NSManagedObject {

// Insert code here to add functionality to your managed object subclass
    class func addMusics(music:Music, channel:Channel?){
        let  appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let  context = appDelegate.managedObjectContext;
        var newMusics = NSEntityDescription.insertNewObjectForEntityForName("Musics", inManagedObjectContext: context) as! Musics
        newMusics.pic_200 = music.pic_500 as String
        newMusics.source = music.source as String
        newMusics.userName = music.user.objectForKey("name") as? String
        newMusics.userAvatar_50 = music.user.objectForKey("avatar_50") as? String
        if (channel == nil){
            newMusics.channelName = music.channel.objectForKey("name") as? String
            newMusics.channelPic = music.channel.objectForKey("pic") as? String
        }else{
            newMusics.channelName = channel!.name  as String
            newMusics.channelPic = channel!.pic_100 as String
        }
        
        newMusics.length = music.length.intValue
        newMusics.musicName = music.name as String
        newMusics.commentCount = music.like_count.intValue
        newMusics.info = music.info as String
        
        do {
            try context.save();
            NSNotificationCenter.defaultCenter().postNotificationName("newMusic", object: nil);//添加新音乐
        } catch {
            // deal with error
            print("保存失败！");
        }
    }
    
    class func getAllDownMuics()->NSMutableArray {
        let  appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let  context = appDelegate.managedObjectContext;
        var fetchRequest = NSFetchRequest();
        let entity = NSEntityDescription.entityForName("Musics", inManagedObjectContext: context)
        fetchRequest.entity = entity;
        let resultArray = NSMutableArray()
        do {
            let fetchedObjects = try context.executeFetchRequest(fetchRequest);
            for var info in fetchedObjects{
                resultArray.addObject(info)
            }
        } catch {
            // deal with error
            print("获取数据失败");
        }
        return resultArray;
    }
    
    class func deleteMuics(music:Musics)->Bool {
        let  appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let  context = appDelegate.managedObjectContext;
        context.delete(music)
        do {
            try context.save();
            return true;
        } catch {
            // deal with error
            print("删除失败");
            return false;
        }
    }
}
